<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :maskClosable="false" :title="title" width="80%" :min-height="500" @ok="handleSubmit">
      <BasicForm @register="registerForm" name="WmItemForm" >
        <template #fileCode="{model,field}">
          <div class="flex flex-row align-top">
            <img ref="print" id="printContent" style="width: 150px;height:150px" :src="model[field]" />
            <div class="flex flex-col">
              <a-button class="mt-2" type="primary" size="small" @click="downloadCode(model[field],model['name'])">下载</a-button>
              <a-button class="mt-2" type="primary" size="small" @click="onPrint">打印</a-button>
            </div>
          </div>
        </template>
      </BasicForm>
      <WmProductBomList :item-id="productItem.id" v-if="productItem" />
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../WmItem.data';
    import {saveOrUpdate} from '../WmItem.api';
    import WmProductBomList from "./WmProductBomList.vue";
    import {downloadByBase64} from "@/utils/file/download";
    import {printJS} from "@/hooks/web/usePrintJS";
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const isDetail = ref(false);
    const productItem = <any>ref(null)
    //表单配置
    const [registerForm, { setProps,resetFields, setFieldsValue, validate, scrollToField }] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        productItem.value=null
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        isDetail.value = !!data?.showFooter;
        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
            productItem.value = data.record
        }else {
          const catalogId = data.catalog?data.catalog['key']:null
          await setFieldsValue({
            wmItemTypeId:catalogId
          })
          productItem.value=null
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));

    function downloadCode(code,fname){
      const filename = fname+'.png'
      downloadByBase64(code,filename,'png')
    }

    function onPrint() {
      printJS({
        printable: '#printContent',
        type: 'html',
      });
    }

    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } catch ({ errorFields }) {
           if (errorFields) {
             const firstField = errorFields[0];
             if (firstField) {
               scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
             }
           }
           return Promise.reject(errorFields);
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
